//
//  CarLocationViewController.m
//  Park
//
//  Created by 123456 on 2017/12/26.
//  Copyright © 2017年 YTYangK. All rights reserved.
//

#import "CarLocationViewController.h"
#import "SelectCarViewModel.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
#import <MapKit/MapKit.h>
#import "KCAnnotation.h"

@interface CarLocationViewController ()<MKMapViewDelegate>
{
    NSString *Lon;
    NSString *lat;
    NSString *Direction;//方向
    NSString *OnlineStatus;//状态
    NSString *RegName;//车牌
    NSString *Speed;//速度
    CLLocationManager *_locationManager;
    KCAnnotation *annotation1;//大头针
    BOOL _firstDisplay; //是否第一loading
    dispatch_source_t _timer;
    int i;

}
@property (weak, nonatomic) IBOutlet MKMapView *CarLocationMapView;
@end

@implementation CarLocationViewController


-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];

    // 关闭定时器
    dispatch_source_cancel(_timer);

    
}


- (void)viewDidLoad {
    [super viewDidLoad];
// Do any additional setup after loading the view from its nib.
    i=0;
    _firstDisplay = YES;

    self.title = @"地图";

    [self startGCDTimer];
    
    //设置代理
    self.CarLocationMapView.delegate=self;
    
    //请求定位服务
    _locationManager=[[CLLocationManager alloc]init];
    
    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
        [_locationManager requestWhenInUseAuthorization];
        
    }
    
    //用户位置追踪(用户位置追踪用于标记用户当前位置，此时会调用定位服务)
    self.CarLocationMapView.userTrackingMode=MKUserTrackingModeFollow;
    //设置地图类型
    self.CarLocationMapView.mapType=MKMapTypeStandard;
    self.CarLocationMapView.showsUserLocation = YES;
    //设置定位精度
    _locationManager.desiredAccuracy=kCLLocationAccuracyBestForNavigation;
    //定位频率,每隔多少米定位一次
    CLLocationDistance distance=20.0;//十米定位一次
    _locationManager.distanceFilter=distance;


}


-(void)request{
    
    
    AFHTTPSessionManager *manager = [NetRequestClss sharedNetRequestClss].sessionManager;

    NSString *pas = [NSString stringWithFormat:@"%@",[self stringToMD5:@"123456"]];

    [manager POST:@"https://weapp.daovay.com/Interface/GetVehicleByIDAjax?" parameters:@{@"pUserCode":@"xkzkadmin",@"pPassword":pas,@"pVehicleIDs":@"8177"} progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary* json = [NSJSONSerialization
                              JSONObjectWithData:responseObject
                              options:kNilOptions
                              error:nil];
        
        NSString  *jsonStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

        NSLog(@"%@",json);
        NSLog(@"%@",jsonStr);

        NSArray *arr = json[@"obj"];
        for (NSDictionary *dict in arr) {
            Lon = dict[@"OffsetLon"];
            lat = dict[@"OffsetLat"];
            OnlineStatus = dict[@"OnlineStatus"];
            RegName =dict[@"RegName"];
            Speed = dict[@"Speed"];
            
            [self deleteAll];
        CLLocationCoordinate2D location1=CLLocationCoordinate2DMake(lat.doubleValue,Lon.doubleValue);
                //地理编码类
                CLGeocoder *geocoder = [[CLGeocoder alloc]init];
                //生成一个location
                CLLocation *location = [[CLLocation alloc]initWithLatitude:location1.latitude longitude:location1.longitude];
                [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
                    if (error)
                    {
                        NSLog(@"反向地理编码失败,error==%@",error);
                    }else
                    {
                        annotation1=[[KCAnnotation alloc]init];
                        CLPlacemark *mark = [placemarks firstObject];
                        annotation1.title=[NSString stringWithFormat:@"%@",RegName];
                        annotation1.subtitle=[NSString stringWithFormat:@"%@%@%@%@%@",mark.country,mark.administrativeArea,mark.locality,mark.subLocality,mark.name];
                        
                        annotation1.image = [UIImage imageNamed:@"车辆坐标"];
                        annotation1.coordinate=location1;
                        
                        [self.CarLocationMapView addAnnotation:annotation1];
                        [self.CarLocationMapView selectAnnotation:annotation1 animated:YES];

                        
                    }
                    if (_firstDisplay == YES) {
                        [self.CarLocationMapView showAnnotations:self.CarLocationMapView.annotations animated:YES];
                    }
                }];
                        
            

        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];
    
    
}

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString *key1=@"AnnotationKey1";
        MKAnnotationView *annotationView=[self.CarLocationMapView dequeueReusableAnnotationViewWithIdentifier:key1];
        
        //如果缓存池中不存在则新建
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允许交互点击
//            annotationView.animatesDrop = YES;
            annotationView.calloutOffset=CGPointMake(0, 0);//定义详情视图偏移量
            

//            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//            [button setBackgroundImage:[UIImage imageNamed:@"进入列表按钮"] forState:UIControlStateNormal];
//            button.backgroundColor = [UIColor clearColor];
//            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            button.frame = CGRectMake(0, 0, 60, 50);
//            [button addTarget:self action:@selector(menu) forControlEvents:UIControlEventTouchUpInside];
//            annotationView.rightCalloutAccessoryView = button;
            
        }
        
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation=annotation;
        annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片
        return annotationView;
    }else {
        return nil;
    }
}



-(void) startGCDTimer{

    // GCD定时器
    NSTimeInterval period = 20.0; //设置时间间隔
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
    // 事件回调
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Count");
            i++;
            if (i>=2) {
                _firstDisplay = NO;
            }
            [self request];
        });
    });
    
    // 开启定时器
    dispatch_resume(_timer);
    
}

- (void)deleteAll
{
    //删除地图上所有的大头针
    [self.CarLocationMapView removeAnnotations:self.CarLocationMapView.annotations];
}


-(NSString *)stringToMD5:(NSString *)str
{
    
    const char *fooData = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(fooData, (CC_LONG)strlen(fooData), result);
    
    NSMutableString *saveResult = [NSMutableString string];
    
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [saveResult appendFormat:@"%02x", result[i]];
    }
    
    return saveResult;
}


@end
